/*
 * @lc app=leetcode.cn id=40 lang=cpp
 *
 * [40] 组合总和 II
 */

// @lc code=start
class Solution {
    vector<int> track;
    vector<vector<int>> res;
    int sum = 0;

    void backtrack(vector<int>& nums, int start, int target) {
        if (sum == target) {
            res.emplace_back(track);
            return;
        }

        if (sum > target) return;

        for (int i = start; i < nums.size(); ++i) {
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            track.emplace_back(nums[i]);
            sum += nums[i];
            backtrack(nums, i + 1, target);
            sum -= nums[i];
            track.pop_back();
        }
    }

public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        backtrack(candidates, 0, target);
        return res;
    }
};
// @lc code=end

